﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Visifire.Charts;
using System.Windows;
using System.Windows.Controls;

namespace EnerForecast
{
    class ChartHelper
    {
        private Chart m_chart;
        public Chart CreatChart(ChartInformation ci)
        {
            m_chart= new Chart();
            Title title = new Title();
            title.Text = ci.title;
            m_chart.Titles.Add(title);

            Axis m_axisX = new Axis();
            m_axisX.Title = ci.m_axisXTitle;
            ////////////////////////////////////////////////
            m_axisX.Interval = 1;
            //////////////////////////////////////////////////
            m_chart.AxesX.Add(m_axisX);

            Axis m_axisY = new Axis();
            m_axisY.Title = ci.m_axisYTitle;
            m_axisY.Enabled = true;
            m_axisY.AxisType = AxisTypes.Primary;
            m_chart.AxesY.Add(m_axisY);

            for (int i = 0; i < ci.dsc.Count; i++)
            {
                DataSeries ds = new DataSeries();
                ds.LegendText = ci.dsc[i].LegendText;
                ds.RenderAs = ci.dsc[i].RenderAs;
                ds.AxisYType = ci.dsc[i].AxisYType;
                ds.DataPoints = new DataPointCollection(ci.dsc[i].DataPoints);
                
                m_chart.Series.Add(ds);
            }
            //添加图例点击响应事件
            SetLegendwithClickHandler();
            //添加绘制时响应事件
            m_chart.Rendered += new EventHandler(Chart_Rendered);
            
            return m_chart;
        }

        

        private void SetLegendwithClickHandler()
        {
            foreach (var serie in m_chart.Series)
            {
                Legend legend = new Legend();
                
                legend.MouseLeftButtonDown+=new EventHandler<LegendMouseButtonEventArgs>(legend_MouseLeftButtonDown);
                m_chart.Legends.Add(legend);
            }
        }
        void legend_MouseLeftButtonDown(object sender, LegendMouseButtonEventArgs e)
        {
            DataSeries ds = e.DataSeries;
            if (ds != null)
            {
                if(ds.Opacity==1){
                    ds.Opacity = 0;
                }else{
                    ds.Opacity = 1;
                }
            }
        }
        void Chart_Rendered(object sender,EventArgs e)
        {
            Chart c = sender as Chart;
            Legend legend = c.Legends[0];
            Grid root = legend.Parent as Grid;
            //int i = root.Children.Count;
            for (int i = 6; i < root.Children.Count; i++)
            {
                if (root.Children[i].GetType().Name.ToString()=="Border")
                {
                    root.Children.RemoveAt(i);
                    root.Children.RemoveAt(i);
                }
            }
        }
    }
}
